<?php
namespace app\admin\controller;
use think\Db;
use think\facade\Request;
use think\facade\Env;
class UpFiles extends Base
{
    protected $uploadValidate = ['file' => [
        // 限制文件大小(单位b)，这里限制为4M
        //'fileSize' => 4 * 1024 * 1024,
        // 限制文件后缀，多个后缀以英文逗号分割
        'fileExt'  => 'jpg,png,gif,jpeg,rar,zip,avi,rmvb,3gp,flv,mp3,txt,doc,xls,ppt,pdf,xls,docx,xlsx,doc'
        // 更多规则请看“上传验证”的规则，文档地址https://www.kancloud.cn/manual/thinkphp6_0/1037629#_444
    ]];
    /**
     * 文件上传
     * @return false|string
     */

    public function uploadadmin()
    {
        // 获取表单上传文件
        $file = request()->file('file');

        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile( 'Admin', $file);
        $src = '/uploads/'.$savename;

        // $savename topic/20200205\a745d8f3fa884fa46b3563d581d3135c.jpeg
        return json(['code' => 0, 'path' => $savename,'data' => array('src' => $src, 'title' => $src)]);
    }

    public function upload(){
        $fileKey = array_keys(request()->file());
        $file = request()->file($fileKey['0']);
        $info = validate($this->uploadValidate)->check(['file' => $file]);
        if($info){
            $result['code'] = 1;
            $result['info'] = '图片上传成功!';
            $path=str_replace('\\','/',$info = \think\facade\Filesystem::disk('public')->putFile( 'Admin', $file));
            $result['url'] = '/uploads/'. $path;
            return $result;
        }else{
            // 上传失败获取错误信息

            $result['code'] =0;
            $result['info'] =  $file->getError();
            $result['url'] = '';
            return $result;
        }
    }


    /**
     * ajax删除图片
     */
    public function delImg ()
    {
        if (Request::post() && Request::isAjax()) {
            $img_url = Request::param('img_url');
            if (!empty($img_url)) {
                $old_img = array(
                    ROOT_PATH . $img_url
                );
                //dump($old_img);die;
                foreach ($old_img as $v) {
                    if (file_exists($v)) {
                        @unlink($v);
                    }
                }
            }
            return json(array('status' => 1, 'info' => '图片成功'));
        } else {
            halt('页面不存在');
        }
    }
}